package com.dotflat.fin.service.impl;

import com.dotflat.fin.PO.FinPlanOrderPO;
import com.dotflat.fin.cnst.Const;
import com.dotflat.fin.domain.FinPlan;
import com.dotflat.fin.domain.FinPlanOrder;
import com.dotflat.fin.repository.FinPlanOrderRepository;
import com.dotflat.fin.service.FinPlanOrderService;
import com.dotflat.fin.service.FinPlanService;
import com.dotflat.rest.service.impl.AreableObjectBaseServiceImpl;
import com.matt.commons.dto.sso.StaffDTO;
import com.matt.commons.exception.BusinessException;
import com.matt.domain.Clientele;
import com.matt.domain.Contract;
import com.matt.foundation.model.ErrorCode;
import com.matt.service.ContractService;
import com.matt.service.TeachCallService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 订单信息service
 *
 * @author ：Ron
 * @date ：Created in 2020/10/30 13:06
 */
@Service
public class FinPlanOrderServiceImpl extends AreableObjectBaseServiceImpl<FinPlanOrder, FinPlanOrderRepository> implements FinPlanOrderService {

    @Override
    @Autowired
    public void setBaseRepository(FinPlanOrderRepository baseRepository) {
        super.setBaseRepository(baseRepository);
    }

    @Autowired
    private TeachCallService teachCallService;

    @Autowired
    private ContractService contractService;

    @Autowired
    private FinPlanService finPlanService;

    @Override
    public FinPlanOrder get(String id){
        FinPlanOrder ret = baseRepository.getOne(id);
        return ret;
    }

    @Override
    public FinPlanOrder notifyParent(String areaId, String staffId, String id){
        FinPlanOrder ret = get(areaId, staffId, id);

        notifyParent(areaId, ret);

        return ret;
    }

    @Override
    public FinPlanOrder notifyParent(String areaId, FinPlanOrder ret){

        if (ret.getNotified()){
            return ret;
        }

        teachCallService.notifyPayOrder(areaId, ret.getClienteleId(),
                ret.getChildName(), ret.getCreatedBy(), ret.getTitle(), ret.getTotalAmount().toString(), null,
                Const.RES_TYPE.PRODUCT.codeOf(), ret.getId());

        ret.setNotified(true);
        baseRepository.save(ret);

        return ret;
    }

    @Override
    public FinPlanOrder cancel(String areaId, String staffId, String id){
        FinPlanOrder order = get(areaId, staffId, id);

        if (order.getPayStatus() != 0){
            throw new BusinessException(ErrorCode.CONTRACT_CODE_ERROR, "收费单已经支付或者正在支付");
        }

        order.setCancelled(true);
        baseRepository.save(order);

        //减掉收费计划的计数器
        FinPlan plan = finPlanService.get(areaId, staffId, order.getPlanId());
        if (plan != null && plan.getOrderCount() > 0){
            plan.setOrderCount(plan.getOrderCount() - 1);
            finPlanService.update(plan);
        }

        return order;
    }

    @Override
    public List<FinPlanOrder> findAllByClienteleIds(List<String> clienteleIds, Integer payStatus, Integer audit, Integer archive){
        if (clienteleIds == null || clienteleIds.size() == 0){
            return new ArrayList<>();
        }

        FinPlanOrderPO param = new FinPlanOrderPO();

        param.setAudited(audit);
        param.setArchived(archive);
        param.setPayStatus(payStatus);
        param.setClienteleIds(clienteleIds);

        List<FinPlanOrder> result = list(null, null, param);

        return result;

//        if (payStatus != null) {
//            return baseRepository.findAllByClienteleIdInAndPayStatusAndCancelledIsFalse(clienteleIds, payStatus);
//        }else{
//            return baseRepository.findAllByClienteleIdInAndCancelledIsFalse(clienteleIds);
//        }

    }

    @Override
    public Contract createContractByPlan(StaffDTO staff, Clientele clientele, FinPlan plan, int index,
                                         BigDecimal totalAmount, String productRecords){
        //合同号
        String orderSnBase = (plan == null)?null:plan.getOrderSnBase();
        String orderNO = null;
        if (StringUtils.isEmpty(orderSnBase)){
            long secs = System.currentTimeMillis()/1000;
            orderNO = String.format("%d-%04d", secs, index);
        }else{
            String p2 = String.valueOf((long) (Math.random() * Long.MAX_VALUE)).substring(0, 3);
            orderNO = String.format("%s-%s-%03d", orderSnBase, p2, index);
        }

        String planName = (plan == null)?"":plan.getName();

        Date beginDate = (plan == null)?null:plan.getBeginDate();
        Date endDate = (plan == null)?null:plan.getEndDate();

        Contract saveContract = contractService.createContract(staff, clientele, planName, orderNO,
                beginDate, endDate, totalAmount, productRecords);

        return saveContract;
    }


}
